package org.opencare.plugins.model;

import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.TimeZone;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;


public class TwitterClient {
	/** Logger for this class and subclasses */
	protected final Log logger = LogFactory.getLog(getClass());
	private Twitter twitter;
	private Status status;
	private BitLyImpl bitly;

	public TwitterClient(String twitterID, String twitterPassword) {
		super();
		// TODO Auto-generated constructor stub
		//twitter = new Twitter(twitterID, twitterPassword);
		twitter = new TwitterFactory().getInstance();
		bitly = new BitLyImpl("opencare","R_bc870ee2e3c2a14635be4586be9c0564");
	}

	public String tweet(MessageObject message) {
		
		String mapPath = "";
		String tweetText = "";
		int pathLength = 0;
		int tweetLength = 140;
		
		tweetText = message.getDescription().trim();
		
		/* String[] tmpText = tweetText.split( ",\\s*", 2);
		
		SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z",Locale.US);
		sdf.setTimeZone(TimeZone.getTimeZone("Asia/Bangkok"));
		String localDate = sdf.format(message.getPubDate()); 
		
		tweetText = "On " + localDate + "," + tmpText[1];*/
				
		if(!message.getMapPath().equalsIgnoreCase("")){
			mapPath = bitly.shorten(message.getMapPath());
			mapPath = "... " + mapPath;			
			pathLength = mapPath.length();			
			tweetLength -= pathLength;		
						
			logger.debug("mapPath: " + mapPath);
			logger.debug("tweetLength: " + tweetLength);
		}
		
		
		tweetText = tweetText.substring(0, tweetLength-1);
		tweetText += mapPath;
				
		logger.debug("tweetText: " + tweetText);
		
		try {
			status = twitter.updateStatus(tweetText);
		} catch (TwitterException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return status.getText();

	}
}
